import http.cookies
from datetime import datetime

# 固定User-Agent
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"

def parse_cookie_string(cookie_str: str) -> dict:
    """解析Cookie字符串为字典"""
    cookies = {}
    for item in cookie_str.split(';'):
        item = item.strip()
        if '=' in item:
            key, value = item.split('=', 1)
            cookies[key] = value
    return cookies

def extract_csrf_from_cookie(cookies_dict: dict) -> str:
    """从Cookie中提取CSRF Token（bili_jct）"""
    csrf = cookies_dict.get('bili_jct', '')
    return csrf

def format_coin(coin_amount: int, coin_type: str) -> str:
    """格式化瓜子金额为“金/银瓜子+元”格式"""
    if coin_type == 'gold':
        yuan = coin_amount / 1000  # 金瓜子1000=1元
        # return f"{coin_amount}金瓜子(¥{yuan:.2f})"
        return f"¥{yuan:.2f}"
    else:
        return f"{coin_amount}银瓜子"

def get_current_time() -> str:
    """获取当前时间字符串（用于日志）"""
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")


def extract_sess_data_from_cookie(cookies_str: str) -> str:
    """
    从Cookie字符串中提取SESSDATA的值，并将逗号(,)替换为%2C、星号(*)替换为%2A

    参数:
        cookies_str: 包含多个Cookie键值对的字符串（格式如"key1=value1; key2=value2"）

    返回:
        处理后的SESSDATA值，如果未找到则返回空字符串
    """
    # 按分号分割Cookie键值对
    cookie_parts = cookies_str.split(';')

    for part in cookie_parts:
        # 去除前后空格（处理类似" SESSDATA=xxx"的情况）
        part = part.strip()

        # 分割键和值（只分割第一个"="，避免值中包含"="的情况）
        if '=' in part:
            key, value = part.split('=', 1)

            # 找到SESSDATA对应的键
            if key == 'SESSDATA':
                # 替换特殊字符：, -> %2C  * -> %2A
                encoded_value = value.replace(',', '%2C').replace('*', '%2A')
                return encoded_value

    # 未找到SESSDATA时返回空字符串
    return ""
